const fs = require('fs')
const cwd = process.cwd()
const ora = require('ora')
const path = require('path')
const inquirer = require('inquirer')
const { messageBox } = require('./tools')
const jsonPath = path.join(cwd, './articles.json')

let articleJson = {}
try {
  articleJson = require(jsonPath)
} catch (error) {}

const spinner = ora()
spinner.color = 'green'

const articleInfoPrompts = [
  {
    type: 'input',
    name: 'title',
    message: `请输入文章标题：`,
    validate(val) {
      if (!val) return chalk.red('请输入项目描述')
      else return true
    }
  },
  {
    type: 'input',
    name: 'category',
    message: `请输入文章的所属分类：`
  },
  {
    type: 'input',
    name: 'tag',
    message: `请输入文章的所属标签，以英文逗号分隔：`
  }
]

// 插入 JSON 配置项
const insertConfig = (article) => {
  messageBox.info('写入 JSON 配置项')
  spinner.text = '正在写入 JSON 配置项';
  spinner.start()
  return new Promise(resolve => {
    const date = new Date()
    const Y = date.getFullYear()
    const M = date.getMonth() + 1
    const D = date.getDate()

    article.date = `${Y}/${M}/${D}`
    articleJson.push(article)
    article.tag = article.tag ? article.tag.split(',') : []

    fs.writeFile(
      jsonPath,
      JSON.stringify(articleJson, null, '\t'),
      (err, res) => {
        if (err) throw err
        setTimeout(resolve, 1000)
      }
    )
  })
    .then(() => {
      spinner.succeed('成功写入 JSON 配置项')
      fs.writeFile(
        path.join(cwd, `./articles/${article.title}.md`),
        'hello world',
        (err, res) => {
          if (err) throw err
          spinner.succeed('操作成功')
        }
      )
    })
}

inquirer.prompt(articleInfoPrompts)
  .then(answer => {
    insertConfig(answer)
  })
